<?php
    include_once("../../includes/config.inc.php");
    $model=D('wx_send');
    $customer_id=$_REQUEST['customer_id'];
    
    if($_REQUEST['a']=='send'){
        usleep(500000);//强制睡0.5s
        $id=(int)$_REQUEST['id'];
        //获取token
        $configModel=new Model_CustomerConfig();
        $token=$configModel->getToken($customer_id);
        if (!$token) die(json_encode('无法获取token'));
        
        /****************群发还是预览****************/
        $is_preview=1;
        if($is_preview==1){
            $firstStr='"touser":"o7-rgsnLrVXUvSGCa7TwAD1oi_28"';//第一个字串
            $mass_api_url='https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token='.$token;//接口地址
        }else{
            if($_POST['groupid'] == -1){
                $firstStr='"filter":{"is_to_all":true,"group_id":""}';
            }else{
                $firstStr='"filter":{"is_to_all":false,"group_id":"'.$_POST['groupid'].'"}';
            }
            $mass_api_url='https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token='.$token;
        }
        
        //更新每个图文的封面图片media_id
        $detailArr=$model->where("id='{$id}' or pid='{$id}'")->order('order_num asc,id asc')->dataArr();
        if($detailArr){
            foreach($detailArr as $k=>$v){
                $detailArr[$k]['media_id']=upImage($v['info_pic'],$token);
            }
        }
        
        //获取多图文的media_id
        $siglePageUrl='http://'.$_SERVER['HTTP_HOST'] .'/'.DIR_NAME. "/mobile/send.php?id=";
        $jsonStr = '{"articles":[';
        foreach ($detailArr as $val){
            if(!$val['info_url']) $val['info_url']=$siglePageUrl.$val['id'];//无外链的访问定制页面
            if(strstr($val['msg_content'],"='") || strstr($val['msg_content'],'="')){//引号未转义
                $val['msg_content']=addslashes($val['msg_content']);
            }
            
            $jsonStr .= '{
                "thumb_media_id":"'.$val['media_id'].'",
                 "title":"'.$val['info_title'].'",
                 "content_source_url":"'.$val['info_url'].'",
                 "content":"'.$val['msg_content'].'",
                 "show_cover_pic":"0"
            },';
        }
        $jsonStr = rtrim($jsonStr, ',') . ']}';
        $multiUpApi = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=".$token;
        $multiMediaMsg = http_request_curl($multiUpApi,$jsonStr);

        //推送多图文
        $jsonStr = '{
           '.$firstStr.',
           "mpnews":{"media_id":"'.$multiMediaMsg['media_id'].'"},
           "msgtype":"mpnews"
        }';
        //file_put_contents('cc.txt',$mass_api_url.'--'.$jsonStr,FILE_APPEND);$returnArray['errcode']=0;
        $returnArray = http_request_curl($mass_api_url,$jsonStr);

        if ($returnArray['errcode'] == 0){
            $model->updateById($id,array('is_send'=>1,'send_time'=>time()));
            die(json_encode('suc'));
        }else{
            die(json_encode($returnArray['errmsg']));
        }
        die;
    }
    
    $type=$_REQUEST['cus_type'];
    $id=(int)$_REQUEST['id'];
    if(empty($customer_id) || empty($type) || empty($id)){
        die('缺少必要参数');
    }
    
    if($type==1){//总部群发所有公众号
        $smarty->assign('list',D('customer')->field("id,pid,status,dele_state,type")->where("status = '1' and dele_state = '1' and type = 3")->dataArr());
    }else{//区域群发下属公众号
        $smarty->assign('list',D('customer')->field("id,pid,status,dele_state,type")->where("status = '1' and dele_state = '1' and type = 3 and pid = '{$customer_id}'")->dataArr());
    }
    $smarty->setTpl('send/templates/bunch_send.html')->display();
    
    //上传图片素材取得meida_id
    function upImage($pic,$token) {
        $upFileUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$token."&type=image";
        $imgPath = ROOT_PATH.'data/image_c/'.$pic;
        $data = array('media'=>'@'.$imgPath);
        $info = http_request_curl($upFileUrl,$data);
        if($info['media_id']){
            return $info['media_id'];
        }else{
            die(json_encode('图片素材上传失败'));
        }
    }

    //curl返回数组
    function http_request_curl($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output,ture);
    }